@extends('layouts.app')
@section('title', '购物车')

@section('content')
<div class="row">
<div class="col-lg-offset-1 col-lg-10">
    <div class="panel panel-default">
        <div class="panel-heading">我的购物车</div>
        <div class="panel-body">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>商品信息</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody class="product_list">
                @foreach($cartItems as $item)
                <tr data-id="{{ $item->productSku->id }}">
                    <td>
                        <input type="checkbox" name="select" value="{{ $item->productSku->id }}" {{ $item->productSku->product->on_sale ? 'checked' : 'disabled' }}>
                    </td>
                    <td class="product_info">
                        <div class="preview">
                            <a href="{{ route('products.show', $item->productSku->product_id) }}" target="_blank">
                                <img src="{{ $item->productSku->product->image_url }}" alt="">
                            </a>
                        </div>
                        <div @if(!$item->productSku->product->on_sale) class="not_on_sale" @endif>
                            <span class="product_title">
                                <a href="{{ route('products.show', $item->productSku->product_id) }}" target="_blank">
                                    {{ $item->productSku->product->title }}
                                </a>
                            </span>
                            <span class="sku_title">{{ $item->productSku->title }}</span>
                            @if(!$item->productSku->product->on_sale)
                                <span class="warning">该商品已下架</span>
                            @endif
                        </div>
                    </td>
                    <td>
                        <span class="price">￥{{ $item->productSku->price }}</span>
                    </td>
                    <td>
                        <input type="text" class="form-control input-sm amount" name="amount" value="{{ $item->amount }}" @if(!$item->productSku->product->on_sale) disabled @endif>
                    </td>
                    <td>
                        <button class="btn btn-xs btn-danger btn-remove">移除</button>
                    </td>
                </tr>
                @endforeach
                </tbody>
            </table>

            <div>
                <form action="" class="form-horizontal" role="form" id="order-form">
                    <div class="form-group">
                        <label class="control-label col-sm-3">选择收货地址</label>
                        <div class="col-sm-9 col-md-7">
                            <select name="address" class="form-control">
                                @foreach($addresses as $address)
                                    <option value="{{ $address->id }}">{{ $address->full_address }} {{ $address->contact_name }} {{ $address->contact_phone }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-sm-3">备注</label>
                        <div class="col-sm-9 col-md-7">
                            <textarea name="remark" class="form-control" rows="3"></textarea>
                        </div>
                    </div>

                    <!-- 优惠券 -->
                    <div class="form-group">
                        <label class="control-label col-sm-3">优惠码</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" name="coupon_code">
                            <span class="help-block" id="coupon_desc"></span>
                        </div>
                        <div class="col-sm-4">
                            <button class="btn btn-success" type="button" id="btn-check-coupon">检查</button>
                            <button class="btn btn-danger" type="button" id="btn-cancel-coupon" style="display: none;">取消</button>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-offset-3 col-sm-3">
                            <button type="button" class="btn btn-primary btn-create-order">提交订单</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</div>
@endsection

@section('script')
    <script>
        $(document).ready(function () {
            // 移除商品
            $(".btn-remove").on('click', function () {

                swal({
                    title: '确认要将该商品移除？',
                    icon: 'warning',
                    buttons: ['取消', '确认'],
                    dangerMode: true
                }).then((result) => {
                    if (!result){
                        return;
                    }

                    var sku_id = $(this).closest('tr').data('id');
                    axios.delete('/cart/' + sku_id).then(() => {
                        location.reload();
                    });
                });
            });
            
            // 全选
            $("#select-all").on('click', function () {
                $("input[name='select'][type='checkbox']:not([disabled])").prop('checked', this.checked);
            });

            // 提交订单
            $(".btn-create-order").on('click', function () {
                var req = {
                    items: [],
                    remark: $("#order-form textarea[name='remark']").val(),
                    address_id: $("#order-form select[name='address']").val(),
                    coupon_code: $("input[name='coupon_code']").val(), // 优惠码
                };

                $(".product_list>tr").each(function(index, el){
                    if ($(el).find("input[name='select']").prop('disabled')){
                        return;
                    }

                    req.items.push({
                        sku_id: $(this).data('id'),
                        amount: $(this).find("input[name='amount']").val(),
                    });
                });

                axios.post("{{ route('orders.store') }}", req).then(function (response) {
                    swal('订单提交成功', '', 'success').then(function () {
                        // 跳转到订单详情
                        location.href = '/orders/' + response.data.id;
                    });
                }, function (error) {
                    if (!error.response){
                        return swal('系统错误', '', 'error');
                    }

                    switch (error.response.status) {
                        case 401:
                            return swal('请先登录', '', 'error');
                            break;
                        case 422:
                            var html = '<div>';
                            _.each(error.response.data.errors, function (errors) {
                                _.each(errors, function (error) {
                                    html += error + '<br>';
                                })
                            })
                            html += '</div>';
                            swal({content: $(html)[0], icon: 'error'});
                            break;
                    }
                });
            });

            // 检查优惠券
            $("#btn-check-coupon").on('click',function () {
                var code = $("input[name='coupon_code']").val();
                if (!code){
                    return swal('请输入优惠码', '', 'warning');
                }

                axios.get('/coupon_codes/'+encodeURIComponent(code)).then((response) => {
                    $("#coupon_desc").text(response.data.description);
                    $("input[name='coupon_code']").prop('readonly', true);
                    $("#btn-cancel-coupon").show();
                    $("#btn-check-coupon").hide();
                }, (error) => {
                    if (error.response.status === 404){
                        swal('优惠码不存在', '', 'error');
                    }else if(error.response.status === 403){
                        swal(error.response.data.msg, '', 'error');
                    }else{
                        swal('系统内部错误', '', 'error');
                    }

                });
            });

            // 取消优惠券
            $("#btn-cancel-coupon").on('click', function () {
                $("#coupon_desc").text('');
                $("input[name='coupon_code']").prop('readonly', false);
                $("#btn-cancel-coupon").hide();
                $("#btn-check-coupon").show();
            });
        })
    </script>
@endsection